package com.feifan.monthhelper.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.feifan.monthhelper.R;
import com.feifan.monthhelper.bean.MenstrualSperiodStatisticsBean;
import com.feifan.monthhelper.bean.db.DayRecordBean;
import com.feifan.monthhelper.bean.db.MenstrualRecordBean;
import com.feifan.monthhelper.calendar.CalendarUtils;
import com.feifan.monthhelper.constant.Constant;
import com.feifan.monthhelper.db.DBUtls;
import com.feifan.monthhelper.ui.base.BaseActivity;
import com.feifan.monthhelper.utils.NumberUtils;
import com.feifan.monthhelper.utils.SPUtils;
import com.feifan.monthhelper.wedget.DoubleClickListener;
import com.feifan.monthhelper.wedget.view.CirclePieView;
import com.feifan.monthhelper.wedget.view.CirclePieView2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MenstrualStatisticsActivity extends BaseActivity {

    @BindView(R.id.rl_title)
    View rlTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_menstrual_state)
    TextView tvMenstrualState;
    @BindView(R.id.tv_menstrual_evaluation)
    TextView tvMenstrualEvaluation;
    @BindView(R.id.tv_menstrual_ahead_days)
    TextView tvMenstrualAheadDays;
    @BindView(R.id.keenly_feel_state)
    TextView keenlyFeelState;
    @BindView(R.id.tv_menstrual_blood_state)
    TextView tvMenstrualBloodState;
    @BindView(R.id.tv_love_evaluation)
    TextView tvLoveEvaluation;
    @BindView(R.id.tv_love_num)
    TextView tvLoveNum;
    @BindView(R.id.tv_unsfate_love_num)
    TextView tvUnsfateLoveNum;
    @BindView(R.id.tv_living_habit_evaluate)
    TextView tvLivingHabitEvaluate;
    @BindView(R.id.ll_menstrual_period_statistics)
    LinearLayout llMenstrualPeriodStatistics;
    @BindView(R.id.ll_love_statistics)
    LinearLayout llLoveStatistics;
    @BindView(R.id.ll_habbit_statistics)
    LinearLayout llHabbitStatistics;
    @BindView(R.id.cpv_menstrual_evaluation)
    CirclePieView2 cpvMenstrualEvaluation;
    @BindView(R.id.cpv_love)
    CirclePieView cpvLove;
    @BindView(R.id.cpv_habit_evaluation)
    CirclePieView2 cpvHabitEvaluation;

    //最近三十天的记录
    private List<DayRecordBean> dayRecordBeans;
    //最近三十天的爱爱记录
    private ArrayList<DayRecordBean> loveRecordBeans;
    //最近三十天的习惯记录
    private ArrayList<DayRecordBean> habitRecordBeans;
    //经期统计记录
    MenstrualSperiodStatisticsBean menstrualSperiodStatisticsBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View getTitleView() {
        return rlTitle;
    }

    @Override
    protected void initData() {
        loveRecordBeans = new ArrayList<>();
        habitRecordBeans = new ArrayList<>();
    }

    @Override
    protected void initView() {

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        llHabbitStatistics.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                Intent intent = new Intent(getApplication(), HabbitStatisticsActivity.class);
                intent.putParcelableArrayListExtra(Constant.ConstantName.LAST_30_HABIT, habitRecordBeans);
                startActivity(intent);
            }
        });
        llLoveStatistics.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                Intent intent = new Intent(getApplication(), LoveStatisticsActivity.class);
                intent.putParcelableArrayListExtra(Constant.ConstantName.LAST_30_LOVES, loveRecordBeans);
                startActivity(intent);
            }
        });
        llMenstrualPeriodStatistics.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                Intent intent = new Intent(getApplication(), MenstrualPeriodStatisticsActivity.class);
                intent.putExtra(Constant.ConstantName.LAST_MENSTRUAL_STATISTICS, menstrualSperiodStatisticsBean);
                startActivity(intent);
            }
        });

        dayRecordBeans = DBUtls.queryDayRecordBy(CalendarUtils.getDay(new Date(), -30), CalendarUtils.getDay(new Date(), 0));
        loadMenstrualData();
        initHabitView();
    }

    private void loadLoveData(Date startDate) {
        Disposable disposable = Observable.create((ObservableOnSubscribe<List<DayRecordBean>>) emitter -> {
//            emitter.onNext(DBUtls.queryMenstrualRecordsBy(CalendarAlarmUtils.getDay(new Date(), -90), CalendarAlarmUtils.getDay(new Date(), 0)));
            emitter.onNext(DBUtls.queryDayRecordBy(startDate, CalendarUtils.getDay(new Date(), 0)));
            emitter.onComplete();
        })
                .doOnSubscribe(disposable1 -> showLoadingDialog("加载数据中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .doOnError(o -> dismisDialog())
                .doOnComplete(this::dismisDialog)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    dayRecordBeans = o;
                    initPregnancyView();
                });
        addDisposable(disposable);

    }

    private void loadMenstrualData() {
        Disposable disposable = Observable.create((ObservableOnSubscribe<List<MenstrualRecordBean>>) emitter -> {
//            emitter.onNext(DBUtls.queryMenstrualRecordsBy(CalendarAlarmUtils.getDay(new Date(), -90), CalendarAlarmUtils.getDay(new Date(), 0)));
            emitter.onNext(DBUtls.queryAllMenstrualRecord());
            emitter.onComplete();
        })
                .doOnSubscribe(disposable1 -> showLoadingDialog("加载数据中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(menstrualRecordBeans -> {
                    Collections.sort(menstrualRecordBeans);
                    return menstrualRecordBeans;
                })
                .map(menstrualRecordBeans -> {
                    MenstrualSperiodStatisticsBean menstrualSperiodStatisticsBean = new MenstrualSperiodStatisticsBean();
                    String menstrual_span = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS);
                    int span_period = NumberUtils.StringToInt(menstrual_span.replaceAll("天", ""));
                    if (menstrualRecordBeans.size() > 0) {
                        MenstrualRecordBean menstrualRecordBean = menstrualRecordBeans.get(0);
                        menstrualSperiodStatisticsBean.setMenstrualPeriod(CalendarUtils.getDateSpan(menstrualRecordBean.start_date, menstrualRecordBean.end_date) + 1);
                        menstrualSperiodStatisticsBean.setStartDate(menstrualRecordBean.start_date);
                        menstrualSperiodStatisticsBean.setEndDate(menstrualRecordBean.end_date);
//                        //计算最近一次经期与现在的时间差
//                        int offset = CalendarUtils.getDateSpan(menstrualRecordBean.start_date, new Date());
//                        if(offset > span_period + 7) {
//                            //大于当前时间+7，则直接返回经期延迟
//                            menstrualSperiodStatisticsBean.setState(MenstrualSperiodStatisticsBean.MenstrualState.DELAY);
//                            menstrualSperiodStatisticsBean.setDelayDays(offset - span_period - 7);
//                            return menstrualSperiodStatisticsBean;
//                        }

                        if(menstrualRecordBeans.size() > 1) {
                            //有两个以上周期，则计算最近两个周期的间隔时间
                            int offset = CalendarUtils.getDateSpan(menstrualRecordBeans.get(1).start_date, menstrualRecordBeans.get(0).start_date);
                            if(offset > span_period + 7) {
                                menstrualSperiodStatisticsBean.setState(MenstrualSperiodStatisticsBean.MenstrualState.DELAY);
                                menstrualSperiodStatisticsBean.setDelayDays(offset - span_period);
                            } else if(offset >= span_period - 7) {
                                menstrualSperiodStatisticsBean.setState(MenstrualSperiodStatisticsBean.MenstrualState.NORMAL);
                            } else {
                                menstrualSperiodStatisticsBean.setState(MenstrualSperiodStatisticsBean.MenstrualState.AHEAD);
                                menstrualSperiodStatisticsBean.setDelayDays(span_period - offset);
                            }
                        }
                    }
                    return menstrualSperiodStatisticsBean;
                })
                .map(menstrualSperiodStatisticsBean -> {
                    if(menstrualSperiodStatisticsBean.getStartDate() == null ) return menstrualSperiodStatisticsBean;
                    List<DayRecordBean> dayRecordBeans = DBUtls.queryDayRecordBy(menstrualSperiodStatisticsBean.getStartDate(), menstrualSperiodStatisticsBean.getStartDate());
                    if(dayRecordBeans != null && dayRecordBeans.size() > 0) {
                        int size = dayRecordBeans.size();
                        int painLevel = 0;
                        int bloodLevel = 0;
                        for(DayRecordBean recordBean : dayRecordBeans) {
                            painLevel += recordBean.pain_level;
                            bloodLevel += recordBean.blood_level;
                        }
                        if(painLevel == 0) {
                            painLevel = -1;
                        }
                        if(bloodLevel == 0) {
                            bloodLevel = -1;
                        }
                        menstrualSperiodStatisticsBean.setBloodLevel(bloodLevel/size);
                        menstrualSperiodStatisticsBean.setPainLevel(painLevel/size);
                    }
                    return menstrualSperiodStatisticsBean;
                })
                .doOnError(o -> dismisDialog())
                .doOnComplete(this::dismisDialog)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    menstrualSperiodStatisticsBean = o;
                    updateMenstrualView(o);

                    loadLoveData(o.getStartDate());
                });
        addDisposable(disposable);
    }

    private void updateMenstrualView(MenstrualSperiodStatisticsBean statisticsBean) {
        tvMenstrualAheadDays.setText(String.format("%d天", statisticsBean.getDelayDays()));
        if(statisticsBean.getBloodLevel() == -1) {
            tvMenstrualBloodState.setText("未记录");
        } else {
            tvMenstrualBloodState.setText(String.format("%d级", statisticsBean.getBloodLevel()));
        }
        if(statisticsBean.getPainLevel() == -1) {
            keenlyFeelState.setText("未记录");
        } else {
            keenlyFeelState.setText(String.format("%d级", statisticsBean.getPainLevel()));
        }
        String evaluation = getResources().getString(R.string.menstrual_normal);
        if(statisticsBean.getState() == MenstrualSperiodStatisticsBean.MenstrualState.DELAY) {
            evaluation = getResources().getString(R.string.menstrual_late);
        } else if (statisticsBean.getState() == MenstrualSperiodStatisticsBean.MenstrualState.AHEAD) {
            evaluation = getResources().getString(R.string.menstrual_ahead);
        }
        tvMenstrualEvaluation.setText(evaluation);
        tvMenstrualState.setText(String.format("%s:", evaluation));
        int score = 100 - statisticsBean.getDelayDays() * 7;
        cpvMenstrualEvaluation.setArcPercent(score < 0 ? 0 : score);
    }

    private void initPregnancyView() {
        int loves = 0;
        int ovulatoryLoves = 0;
        int pregnancy = 0;
        for (DayRecordBean recordBean : dayRecordBeans) {
            if (recordBean.protects != null) {
                loveRecordBeans.add(recordBean);
                loves++;
                LogUtils.d("db data : ", recordBean == null, GsonUtils.toJson(recordBean));
                if (recordBean.state == Constant.MenstrualState.OVULATORY_DAY) {
                    ovulatoryLoves++;
                    if (recordBean.protects != null && recordBean.protects.contains("无措施")) {
                        pregnancy = Constant.Percent.HIGH;
                    } else if (pregnancy < Constant.Percent.LOW) {
                        pregnancy = Constant.Percent.LOW;
                    }
                } else if (recordBean.state == Constant.MenstrualState.MENSTRUAL_DAY) {
                    if (pregnancy < Constant.Percent.LOW) {
                        pregnancy = Constant.Percent.LOW;
                    }
                } else {
                    if (recordBean.protects.contains("无措施")) {
                        pregnancy = Constant.Percent.MIDDLE;
                    } else if (pregnancy < Constant.Percent.LOW) {
                        pregnancy = Constant.Percent.LOW;
                    }
                }
            }
        }

        tvLoveNum.setText(loves + "次");
        tvUnsfateLoveNum.setText(ovulatoryLoves + "次");
        cpvLove.setArcPercent(pregnancy);
        String pregnancyStr;
        if (pregnancy == Constant.Percent.HIGH) {
            pregnancyStr = getResources().getString(R.string.high_pregnancy);
        } else if (pregnancy == Constant.Percent.MIDDLE) {
            pregnancyStr = getResources().getString(R.string.mid_pregnancy);
        } else {
            pregnancyStr = getResources().getString(R.string.low_pregnancy);
        }
        tvLoveEvaluation.setText(pregnancyStr);
    }

    private void initHabitView() {
        int habits = 0;
        for (DayRecordBean recordBean : dayRecordBeans) {
            if (recordBean.breakfast || recordBean.defecate || recordBean.fruit || recordBean.hot_water || recordBean.sports) {
                habitRecordBeans.add(recordBean);
                habits++;
            }
        }
        int habitPrecent;
        String habitStr;
        if (habits < 10) {
            habitPrecent = habits * 6;
            habitStr = getResources().getString(R.string.not_good);
        } else if (habits < 20) {
            habitPrecent = (habits - 10) * 2 + 60;
            habitStr = getResources().getString(R.string.good);
        } else if (habits < 30) {
            habitPrecent = (habits - 10) * 2 + 80;
            habitStr = getResources().getString(R.string.very_good);
        } else {
            habitPrecent = 100;
            habitStr = getResources().getString(R.string.very_good);
        }
        cpvHabitEvaluation.setArcPercent(habitPrecent);
        tvLivingHabitEvaluate.setText(habitStr);
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_menstrual_statistics;
    }
}
